<template>
  <div>
    <router-link
      v-if="questionnaire.replyCount"
      :to="`/${$rp.QUESTIONNAIRES}/${questionnaire.id}/results`"
      class="m-l-auto el-button el-button--primary el-button--small"
      v-text="'统计'"
    />
    <router-link
      :to="`/${$rp.QUESTIONNAIRES}/${questionnaire.id}/${$rp.RELEASE}`"
      class="el-button el-button--success el-button--small"
      v-text="questionnaire.released ? '重新发布' : '发布'"
    />
    <el-button
      size="small"
      title="复制一份问卷"
      @click="copyQuestionnaire"
      :loading="loading">
      复制
    </el-button>
    <router-link
      v-if="!questionnaire.released"
      class="el-button el-button--primary el-button--small is-plain"
      :to="`/${$rp.QUESTIONNAIRES}/${questionnaire.id}/${$rp.UPDATE}`"
      v-text="'编辑'"
    />
    <el-button v-else size="small" type="primary" plain disabled title="不能编辑已发布的问卷">编辑</el-button>
    <el-button size="small" type="danger" plain @click="deleteQ">删除</el-button>
  </div>
</template>

<script>
import { formatQuestionnaire } from '@/components/questionnaire/format';

export default {
  name: 'QuestionnairesListItemButtons', // 问卷列表上每一项的操作按钮
  props: {
    questionnaire: { // 这个问卷
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      loading: false,
    };
  },
  methods: {
    // 删除问卷
    deleteQ() {
      const msg = `<div>确认删除问卷 <strong class="el-alert--error is-light is-bold">${this.questionnaire.title}</strong> 吗？</div>`;
      this.$msgbox({
        title: '提示',
        message: msg,
        dangerouslyUseHTMLString: true,
        showCancelButton: true, // 显示取消按钮
        customClass: 'confirm-left',
        confirmButtonText: '确定',
        confirmButtonLoading: false,
        confirmButtonClass: 'el-button--danger',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            Object.assign(instance, {
              confirmButtonLoading: true,
              confirmButtonText: '正在删除...',
            });
            this.$api.questionnaires.delete({ qnId: this.questionnaire.id })
              .then(() => {
                this.$message.success('删除成功');
                this.$emit('deletedQuestionnaire', this.questionnaire);
              })
              .catch(() => {})
              .then(() => done());
          } else done();
        },
      });
    },
    // 复制问卷
    copyQuestionnaire() {
      this.loading = true;
      this.$api.questionnaires.copy({ qnId: this.questionnaire.id })
        .then((res) => {
          this.$message.success('复制成功');
          const qu = Object.assign({}, res.data, { title: `(复制)${res.data.title}` });
          this.$emit('copied', this.questionnaire, formatQuestionnaire(qu));
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
};
</script>

<style></style>
